package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class CheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //1.获取请求路径
        String requestURI = request.getRequestURI();
        log.info("url:{}",requestURI);
        //2.判断请求是否包含login,包含就放行
        if (requestURI.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.否则查看请求头中的令牌
        String jwt = request.getHeader("token");
        log.info("jwt:{}",jwt);
        //4.判断令牌是否存在
        if (!StringUtils.hasLength(jwt)){
            //为空或null,手动转化为JSON格式
            Result error = Result.error("not login");
            String jsonString = JSONObject.toJSONString(error);
            //通过response中的方法返回数据
            response.getWriter().write(jsonString);
            return;
        }

        //5.执行到这里,说明令牌存在,解析令牌
        try {
            //正确不会出错,错误则会爆出异常
            JwtUtils.jwtParse(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("令牌错误");
            Result error = Result.error("jwt error");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return;
        }
        //6.令牌正确,放行
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
